<template>
    <div style=" overflow: auto;height: 60%;width: 80%;position: absolute;top: 50px;">
          <van-cell 
              v-for="i in data" 
              :title="i.type"
              :value="new Date().toLocaleTimeString()"
              :label="i.msg" 
          >
            <template #label v-if="i.type !='用户请求接入'">
                <textarea style="width: 100%;white-space: pre-wrap; overflow-wrap: break-word; padding: 5px;border: none;">{{i.msg}}</textarea>
            </template>
        </van-cell>
    </div>
    <div style="position: absolute;top:70%"> <textarea v-model="msg" placeholder="请输入消息" 
                                            style=" width: 80%;
                                                    height: 200px;
                                                    resize: none; /* 禁止用户调整大小 */
                                                    white-space: pre-wrap; /* 自动换行 */
                                                    overflow-wrap: break-word; /* 单词过长时换行 */
                                                    padding: 5px; /* 可选：调整内边距 */
                                                    "
                                            ></textarea>
  <button @click="sendmes">发送消息</button><button @click="stopws">结束会话</button></div>
  <div style="float: right down; margin-right: 1%;"><div v-for="i in userlist"><button @click="gouser(i)">{{ i }}</button></div></div>
    </template>
    
<script lang="ts" setup>
    import {ref,onMounted}  from 'vue'
    const userid=ref(localStorage.getItem('userid'))
    //搜索用的
    const socket = ref(null)
    const data = ref([])
    const userlist = ref([])
    const room = ref('kf'+userid.value)
    const msg = ref('')
    const sendmes = () => {
        if (!msg.value.trim()) {
            alert('消息不能为空')
            return
        }
        
        try {
            const payload = JSON.stringify({ 
            type: '客服', 
            text: msg.value 
            })
            socket.value.send(payload)
            msg.value = '' // 清空输入框
        } catch (e) {
            console.error('发送失败:', e)
        }
        }
    const gouser=(userroom)=>{
        if (socket.value) {
            socket.value.close(); // 关闭旧连接
        }
        initwesockt(userroom)
    }
    const stopws = () => {
    socket.value.close()
  }
    const initwesockt=(room)=>{
  
        socket.value = new WebSocket("ws://127.0.0.1:8000/room/"+room+"/");
  
        socket.value.onopen = (event)=>{
            console.log("连接成功")
        }
  
        socket.value.onmessage = (event)=>{
            try {
                const parsedData = {
                    msg: JSON.parse(event.data).data,
                    type: JSON.parse(event.data).action,
                  timestamp: new Date().toISOString()
                  };
                  if(parsedData.type=='用户请求接入'){
                    userlist.value.push(parsedData.msg)
                  }
                  data.value = [...data.value, parsedData];

                  console.log(data.value)
                  console.log("收到消息:", parsedData);
            } catch(e) {
                console.error('消息解析失败:', e);
            }
        }
  
        socket.value.onclose = (event)=>{
            console.log("连接关闭")
        }
  
        socket.value.onerror = (error)=>{
            console.error('WebSocket错误:', error)
        }
    
        // // 当断开连接时，触发该函数
        // this.socket.onclose =function (event){
        // let tag = document.createElement("div");
        // tag.innerText = "[连接断开]";
        // document.getElementById("message").appendChild(tag);
        // }
    }
    
    onMounted(()=>{
        initwesockt(room.value)
    })
    </script>
      